package debris

import (
	"AccessAdmin/internal/consts"
	"AccessAdmin/internal/service"
	"context"
	"encoding/base64"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/grand"
	"io"
	"strconv"
	"strings"
)

// 碎片服务

type sDebris struct {
}

func init() {
	service.RegisterDebris(New())
}

func New() *sDebris {
	return &sDebris{}
}

func (s *sDebris) GetBackendPrefix(ctx context.Context) string {
	backendPrefix := g.Cfg().MustGet(ctx, "route.backendPrefix").String()
	if backendPrefix == "" {
		backendPrefix = consts.DefaultBackendPrefix
	}
	return backendPrefix
}

// Base64ToImage base64转图片
func (s *sDebris) Base64ToImage(ctx context.Context, BaseCode string) (string, error) {
	_i := strings.Index(BaseCode, ",")
	dec := base64.NewDecoder(base64.StdEncoding, strings.NewReader(BaseCode[_i+1:]))
	filePath := gtime.Now().Format("Y/m/d")
	uploadDir := g.Cfg().MustGet(ctx, "setting.uploadDir").String() + "/" + filePath
	name := strings.ToLower(strconv.FormatInt(gtime.TimestampNano(), 36)+grand.S(6)) + ".png"
	uploadFile := gfile.Join(uploadDir, name)
	newFile, err := gfile.Create(uploadFile)
	if err != nil {
		return "", err
	}
	defer newFile.Close()
	_, err = io.Copy(newFile, dec)
	if err != nil {
		return "", err
	}
	return filePath + "/" + name, nil
}
